package com.budwk.app.sqfwV2.component;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.IdcardUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.common.config.AppException;
import com.budwk.app.sqfw.component.CommonComponent;
import com.budwk.app.sqfw.constants.CommonConstants;
import com.budwk.app.sqfw.dto.PersonnelTagDTO;
import com.budwk.app.sqfw.models.BuildingInfo;
import com.budwk.app.sqfw.models.HouseInfo;
import com.budwk.app.sqfw.models.PersonInfo;
import com.budwk.app.sqfw.services.BuildingInfoService;
import com.budwk.app.sqfw.services.HouseInfoService;
import com.budwk.app.sqfw.services.PersonInfoService;
import com.budwk.app.sqfwV2.dto.dto.PersonInfoDTO;
import com.budwk.app.sqfwV2.dto.vo.BuildingUnitVo;
import com.budwk.app.sqfwV2.dto.vo.HouseInfoReqVo;
import com.budwk.app.sqfwV2.dto.vo.HouseRelatPerson;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.StrUtil;
import com.budwk.app.util.poiUtils.nutzBeanUtils.NutzIocUtils;
import com.budwk.starter.security.utils.SecurityUtil;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.util.cri.SqlExpressionGroup;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
public class HouseInfoComponent {
    public static void checkSubmitData(HouseInfo reqVo) {
        HouseInfoService houseInfoService = NutzIocUtils.getBean(HouseInfoService.class);
        HouseInfo houseInfo = houseInfoService.fetch(reqVo.getId());
        if (houseInfo == null) {
            throw new AppException("房屋信息不存在！");
        }
        if (houseInfo.isDeleted()) {
            throw new AppException("该房屋已删除，不能更新！");
        }
        reqVo.setBuildingId(houseInfo.getBuildingId());
        BuildingInfoService buildingInfoService = NutzIocUtils.getBean(BuildingInfoService.class);
        BuildingInfo buildingInfo = buildingInfoService.fetch(reqVo.getBuildingId());
        if (CommonConstants.NO_CHINA.equals(houseInfo.getIsFill())) {
            // 记录采集时间
            reqVo.setIsFill(CommonConstants.YES_CHINA).setFillDate(LocalDateTime.now());
            Integer fillNum = buildingInfo.getFillNum() == null ? 1 : buildingInfo.getFillNum() + 1;
            buildingInfo.setFillNum(fillNum).setUpdateTime(LocalDateTime.now()).setUpdateId(SecurityUtil.getUserId());
            // 修改楼栋房屋采集数量
            buildingInfoService.updateIgnoreNull(buildingInfo);
        }
        reqVo.setDetailAddress(houseInfo.getDetailAddress());
        // 检查同一单元下房号是否存在
        if (houseInfo.getRoomNumber().equals(reqVo.getRoomNumber())) {
            return;
        }
        // 房屋号不一致 需要检查是否重名
        HouseInfo houseInfo1 = findByRoom(houseInfo.getUnit(), reqVo.getRoomNumber());
        if (houseInfo1 != null) {
            if (!houseInfo1.getId().equals(reqVo.getId())) {
                throw new AppException("该单位下已存在同名房屋，请勿修改！");
            }
        }
    }

    public static HouseInfo findByRoom(String unit, String roomNumber) {
        Cnd cnd = Cnd.NEW();
        SqlExpressionGroup where = cnd.where();
        where.andEquals(HouseInfo::getUnit, unit).andEquals(HouseInfo::getRoomNumber, roomNumber).andEquals(HouseInfo::isDeleted, false);
        HouseInfoService houseInfoService = NutzIocUtils.getBean(HouseInfoService.class);
        HouseInfo houseInfo = houseInfoService.fetch(cnd);
        return houseInfo;
    }

    public static void initHouseInfo(HouseInfo reqVo, String userId) {
        SysUserService userService = NutzIocUtils.getBean(SysUserService.class);
        Sys_user user = userService.fetch(userId);
        reqVo.setCreateBy(userId).setCreateTime(LocalDateTime.now()).setDeleted(false)
                .setUpdateId(userId).setUpdateTime(LocalDateTime.now())
                .setProvince(user.getProvince())
                .setCity(user.getCity())
                .setDistrict(user.getDistrict())
                .setCounty(user.getCounty())
                .setCommunity(user.getCommunity());
    }

    public static HouseInfo buildHouseInfo(HouseInfoReqVo reqVo, BuildingInfo buildingInfo, Sys_user user, int number) {
        HouseInfo houseInfo = new HouseInfo();
        String floor = reqVo.getFloor();
        // 初始化基本信息
        houseInfo.setUnit(reqVo.getUnit())
                .setFloor(floor)
                .setGrid(buildingInfo.getGrid())
                .setIsLoft(CommonConstants.NO_CHINA)
                .setHouseRisks(CommonConstants.NO_CHINA)
                .setIsFill(CommonConstants.NO_CHINA)
                .setBuildingId(buildingInfo.getId())
                .setHouseNumber(String.valueOf(number))
                .setCreateBy(user.getId())
                .setCreateTime(LocalDateTime.now())
                .setDeleted(false)
                .setUpdateId(user.getId()).
                setUpdateTime(LocalDateTime.now())
                .setProvince(user.getProvince())
                .setCity(user.getCity())
                .setDistrict(user.getDistrict())
                .setCounty(user.getCounty())
                .setCommunity(user.getCommunity());
        String roomNumber = String.format("%s%s%s",reqVo.getFloor(), "0", number);// 房屋号
        // 详细地址（五级 + 小区 + 楼栋 + 单元 + 楼层 + 房号）唯一标识
        String detailAddress = String.format("%s%s%s%s%s%s%s%s%s%s", user.getProvince(), user.getCity(), user.getDistrict(),
                user.getCounty(), user.getCommunity(), buildingInfo.getResidentialArea(), buildingInfo.getBuildingName(),
                reqVo.getUnit(), reqVo.getFloor() + "楼", roomNumber);
        houseInfo.setDetailAddress(detailAddress).setDoorNumber(detailAddress)
                .setRoomNumber(roomNumber);
        return houseInfo;
    }

    public static void updateHouseInfo(BuildingUnitVo buildUnit, String userId, List<HouseInfo> houseInfos, BuildingInfo reqParam) {
        Integer floorHouses = buildUnit.getFloorHouses(); // 每层户数  3
        Integer start = buildUnit.getStartFloor();  // 起始楼层  1

        SysUserService userService = NutzIocUtils.getBean(SysUserService.class);
        HouseInfoService houseInfoService = NutzIocUtils.getBean(HouseInfoService.class);
        Sys_user user = userService.fetch(userId);
        for (int i = start; i <= buildUnit.getFloorsCount(); i++) {
            if (start == 0) {
                start ++; // 楼层不能为0层 默认+1层
                continue;
            }
            for (int j = 1; j <= floorHouses; j++) {
                String floor = String.valueOf(start);
                // 获取当前楼层的所有房屋
                List<HouseInfo> floorHouse = houseInfos.stream().filter(e -> e.getFloor().equals(floor)).collect(Collectors.toList());
                if (CollectionUtil.isEmpty(floorHouse)) {
                    HouseInfoReqVo reqVo = new HouseInfoReqVo();
                    reqVo.setFloor(String.valueOf(start)).setUnit(buildUnit.getUnitName());
                    HouseInfo houseInfo = HouseInfoComponent.buildHouseInfo(reqVo, reqParam, user, j);
                    // 入库操作
                    houseInfoService.insert(houseInfo);
                    continue;
                }
                int finalJ = j;
                Optional<HouseInfo> first1 = floorHouse.stream().filter(e -> e.getHouseNumber().equals(String.valueOf(finalJ))).findFirst();
                if (first1.isEmpty()) {
                    HouseInfoReqVo reqVo = new HouseInfoReqVo();
                    reqVo.setFloor(String.valueOf(start)).setUnit(buildUnit.getUnitName());
                    HouseInfo houseInfo = HouseInfoComponent.buildHouseInfo(reqVo, reqParam, user, j);
                    // 入库操作
                    houseInfoService.insert(houseInfo);
                }
            }
            start ++;
        }
    }

    public static List<PersonnelTagDTO> handleSpecialMark(PersonInfo personInfo, JSONObject newSpecialMark) {
        List<PersonnelTagDTO> personnelTags = personInfo.getSpecialMark();
        if (newSpecialMark == null) {
            return personnelTags;
        }
        // 获取原有的类别
        PersonnelTagDTO newPerson = JSONObject.toJavaObject(newSpecialMark, PersonnelTagDTO.class);
        if (CollectionUtil.isEmpty(personnelTags)) {
            return List.of(newPerson);
        }
        List<PersonnelTagDTO> personnelSpec = new ArrayList<>();
        personnelSpec.add(newPerson);
        for (PersonnelTagDTO personnelTag : personnelTags) {
            if (personnelTag.getBusinessType().equals(newPerson.getBusinessType())) {
                continue;
            }
            PersonnelTagDTO p = new PersonnelTagDTO();
            p.setBusinessType(personnelTag.getBusinessType());
            p.setTag(personnelTag.getTag());
            personnelSpec.add(p);
        }
        personInfo.setSpecialMark(personnelSpec);
        return personnelSpec;
    }
}
